<template>
  <el-dialog
    width="80%"
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="分类" prop="cateId">
            <el-select v-model="dataForm.cateId" placeholder="请选择">
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input type="text" v-model="dataForm.title" placeholder />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input
              v-model="dataForm.sort"
              type="number"
              placeholder="数值越大越靠前"
              style="width: 175px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="简介" prop="brief">
            <el-input type="text" v-model="dataForm.brief" placeholder />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="类型" prop="type">
            <el-radio-group v-model="dataForm.type">
              <el-radio border :label="1">图文信息</el-radio>
              <el-radio border :label="2">图文视频</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="ImgPath">
            <el-upload
              :action="actionImg"
              :file-list="dataForm.ImgPath"
              :on-success="handleImgSuccess"
              :on-remove="handleImgRemove"
              :on-progress="handleImgProgress"
              :on-exceed="handleExceed"
              :before-upload="beforeImageUpload"
              :limit="1"
            >
              <!-- <i class="el-icon-plus"></i>-->
              <el-button type="primary" icon="el-icon-plus">选择图片</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item prop="videoPath" v-if="parseInt(dataForm.type) === 2">
            <el-upload
              :action="actionImg"
              :file-list="dataForm.videoPath"
              :on-success="handleVideoSuccess"
              :on-error="handleVideoError"
              :on-remove="handleVideoRemove"
              :on-exceed="handleExceed"
              :on-progress="handleVideoProgress"
              :before-upload="beforeVideoUpload"
              :limit="1"
            >
              <el-button type="primary" icon="el-icon-plus">选择视频</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联" prop="type">
            <el-row>
              <el-col :span="8">
                <el-button type="primary" style="margin-bottom: 10px" @click="getTestList">选择试题</el-button>
              </el-col>
              <el-col :span="8">
                <el-input type="number" v-model="dataForm.qualifiedCount" placeholder="请输入及格题数"></el-input>
              </el-col>
              <el-col :span="5" :push="3">
                <el-button type="danger" style="margin-bottom: 10px" @click="romTestList">全部清空</el-button>
              </el-col>
            </el-row>
            <el-tabs type="border-card" v-model="testType">
              <el-tab-pane v-for="x in test" :label="x.value" :key="x.key" :name="x.key">
                <el-table
                  v-loading="testLoading"
                  :data="x.selectArray"
                  height="300"
                  style="overflow:auto"
                >
                  <el-table-column prop="info" label="试题内容" />
                  <el-table-column label="操作" width="55" align="center">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        icon="el-icon-delete"
                        @click="deleteTest(scope.row.id)"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="详情" prop="content">
        <ck-editor @change="editorChange" ref="ckEditor" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="loading">确定</el-button>
    </div>
    <el-dialog width="60%" title="试题列表" :visible.sync="innerVisible" append-to-body>
      <el-tabs type="border-card" v-model="testType" @tab-click="testTabChange">
        <el-tab-pane v-for="x in test" :label="x.value" :key="x.key" :name="x.key">
          <el-table
            v-loading="testLoading"
            :ref="x.key"
            :data="x.testData.list[x.testForm.page||search]"
            tooltip-effect="dark"
            @selection-change="handleSelectionChange"
            style="overflow:auto"
          >
            <el-table-column prop="info" label="试题内容" />
            <el-table-column type="selection" width="55" />
          </el-table>
          <el-pagination
            :hide-on-single-page="parseInt(x.testData.Count) < 5"
            :total="parseInt(x.testData.Count)"
            @current-change="testCurrentChange"
            layout="prev, pager, next"
          ></el-pagination>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="selectSubmit">确定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import ckEditor from '@/components/ckEditor/ckEditor'
import Vue from 'vue'

export default {
  data() {
    return {
      isSelect: true,
      test: {
        odd: {
          key: 'odd',
          value: '单选',
          testForm: {
            keyword: '',
            quesCateId: '',
            quesLevel: '',
            page: 1,
            limit: 10
          },
          testData: {
            list: {},
            Count: ''
          },
          selectJson: {},
          selectArray: []
        },
        many: {
          key: 'many',
          value: '多选',
          testForm: {
            keyword: '',
            quesCateId: '',
            quesLevel: '',
            page: 1,
            limit: 10
          },
          testData: {
            list: {},
            Count: ''
          },
          selectJson: {},
          selectArray: []
        },
        judge: {
          key: 'judge',
          value: '判断',
          testForm: {
            keyword: '',
            quesCateId: '',
            quesLevel: '',
            page: 1,
            limit: 10
          },
          testData: {
            list: {},
            Count: ''
          },
          selectJson: {},
          selectArray: []
        }
      },
      visible: false,
      innerVisible: false,
      testType: 'odd',
      dataForm: {
        qualifiedCount: '',
        type: 1,
        id: 0,
        cateId: '',
        title: '',
        brief: '',
        ImgPath: [],
        videoPath: [],
        content: '',
        trainDataQuesIds: [],
        sort: ''
      },
      getTestUrl: {
        odd: '/exam-admin/ques/singer/list',
        many: '/exam-admin/ques/multi/list',
        judge: '/exam-admin/ques/judge/list'
      },
      loading: false,
      testLoading: false,
      cateList: [],
      actionImg:
        this.$http.adornUrl('/oss/oss/upload?token=') +
        Vue.cookie.get('token') +
        '&client=ADMIN',
      // dataListLoading: false,
      dataRule: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        cateId: [{ required: true, message: '请选择分类', trigger: 'change' }],
        brief: [{ required: true, message: '简介不能为空', trigger: 'blur' }]
      }
    }
  },
  components: { ckEditor },
  methods: {
    editorChange (val) {
      this.dataForm.content = val
    },
    selectSubmit() {
      this.innerVisible = false
      Object.values(this.test).forEach(x => {
        let selectJson = x.selectJson
        for (let select in selectJson) {
          if (!x.selectArray.length) {
            x.selectArray = [
              ...x.selectArray,
              ...selectJson[select].map(i => ({
                info: i.info,
                id: i.id,
                page: select
              }))
            ]
          } else {
            x.selectArray = [
              ...x.selectArray.filter(
                j => parseInt(j.page) !== parseInt(select)
              ),
              ...selectJson[select].map(i => ({
                info: i.info,
                id: i.id,
                page: select
              }))
            ]
          }
        }
      })
    },
    resetData(test) {
      if (test) {
        this.test = {
          odd: {
            key: 'odd',
            value: '单选',
            testForm: {
              keyword: '',
              quesCateId: '',
              quesLevel: '',
              page: 1,
              limit: 10
            },
            testData: {
              list: {},
              Count: ''
            },
            selectJson: {},
            selectArray: []
          },
          many: {
            key: 'many',
            value: '多选',
            testForm: {
              keyword: '',
              quesCateId: '',
              quesLevel: '',
              page: 1,
              limit: 10
            },
            testData: {
              list: {},
              Count: ''
            },
            selectJson: {},
            selectArray: []
          },
          judge: {
            key: 'judge',
            value: '判断',
            testForm: {
              keyword: '',
              quesCateId: '',
              quesLevel: '',
              page: 1,
              limit: 10
            },
            testData: {
              list: {},
              Count: ''
            },
            selectJson: {},
            selectArray: []
          }
        }
      } else {
        this.test = {
          odd: {
            key: 'odd',
            value: '单选',
            testForm: {
              keyword: '',
              quesCateId: '',
              quesLevel: '',
              page: 1,
              limit: 10
            },
            testData: {
              list: {},
              Count: ''
            },
            selectJson: {},
            selectArray: []
          },
          many: {
            key: 'many',
            value: '多选',
            testForm: {
              keyword: '',
              quesCateId: '',
              quesLevel: '',
              page: 1,
              limit: 10
            },
            testData: {
              list: {},
              Count: ''
            },
            selectJson: {},
            selectArray: []
          },
          judge: {
            key: 'judge',
            value: '判断',
            testForm: {
              keyword: '',
              quesCateId: '',
              quesLevel: '',
              page: 1,
              limit: 10
            },
            testData: {
              list: {},
              Count: ''
            },
            selectJson: {},
            selectArray: []
          }
        }
        this.dataForm = {
          qualifiedCount: '',
          type: 1,
          cateId: '',
          title: '',
          brief: '',
          ImgPath: [],
          videoPath: [],
          trainDataQuesIds: [],
          content: '',
          sort: ''
        }
      }
    },
    testTabChange() {
      this.getTestList()
    },
    deleteTest(id) {
      this.$confirm(`确定确定要进行删除操作吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          Object.values(this.test[this.testType].selectJson).forEach(x => {
            x.filter((x, i, arr) => {
              if (parseInt(x.id) === parseInt(id)) {
                arr.splice(i, 1)
              }
            })
          })
          this.test[this.testType].selectArray.filter((x, i, arr) => {
            if (parseInt(x.id) === parseInt(id)) {
              arr.splice(i, 1)
            }
          })
        })
        .catch(() => ({}))
    },
    romTestList() {
      this.$confirm(`确定确定要进行删除操作吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.resetData('test')
        })
        .catch(() => ({}))
    },
    testEcho(page) {
      let temporarily = this.test[this.testType].selectJson[page]
      setTimeout(() => this.$refs[this.testType][0].clearSelection(), 50)
      setTimeout(() => {
        this.test[this.testType].selectJson[page] = temporarily
        if (this.test[this.testType].selectJson[page]) {
          this.test[this.testType].selectJson[page].forEach(row => {
            this.$refs[this.testType][0].toggleRowSelection(row)
          })
        }
        this.isSelect = true
      }, 100)
    },
    testCurrentChange(val) {
      this.isSelect = false
      this.test[this.testType].testForm.page = val
      this.getTestList()
    },
    handleSelectionChange(val) {
      this.isSelect && (this.test[this.testType].selectJson[this.test[this.testType].testForm.page] = val)
    },
    getTestList() {
      this.innerVisible = true
      this.testLoading = true
      let data = Object.assign({}, this.test[this.testType].testForm)
      data.page =
        data.keyword || data.quesCateId || data.quesLevel ? '' : data.page
      let list = this.test[this.testType].testData.list[data.page || 'search']
      if (list && list.length > 0) {
        let page = data.page || 'search'
        this.testEcho(page)
        this.testLoading = false
      } else {
        this.$http({
          url: this.$http.adornUrl(this.getTestUrl[this.testType]),
          method: 'post',
          data: data
        })
          .then(res => {
            this.testLoading = false
            if (res && res.code === 200) {
              let page = data.page || 'search'
              this.test[this.testType].testData.list[page] = res.data.list
              this.test[this.testType].testData.Count = res.data.totalCount
              this.test[this.testType].selectArray.forEach(x => {
                if (res.data.list.filter(j => x.id === j.id).length > 0) {
                  x.page = page
                }
                this.test[this.testType].selectJson[page] = [
                  ...(this.test[this.testType].selectJson[page] || []),
                  ...res.data.list.filter(j => x.id === j.id)
                ]
              })
              this.testEcho(page)
            }
            this.dataListLoading = false
          })
          .catch(() => {
            this.testLoading = false
          })
      }
    },
    init(id) {
      this.resetData()
      this.dataForm.id = id || ''
      this.visible = true
      this.$http({
        url: this.$http.adornUrl(`/train/traincate/getList`),
        method: 'post'
      }).then(data => {
        this.cateList = data.data
        this.$nextTick(() => {
          this.$refs['ckEditor'] && this.$refs['ckEditor'].setData('')
          if (this.dataForm.id) {
            this.$http({
              url: `/train/traindata/info/${this.dataForm.id}`,
              method: 'post'
            }).then(res => {
              if (res && res.code === 200) {
                this.dataForm = res.data.trainData
                res.data.trainDataQues &&
                  res.data.trainDataQues
                    .map(x => ({
                      info: x.info,
                      id: x.quesId,
                      type:
                        parseInt(x.quesType) === 1
                          ? 'odd'
                          : parseInt(x.quesType) === 2
                          ? 'many'
                          : 'judge'
                    }))
                    .forEach(x => this.test[x.type].selectArray.push(x))
                this.dataForm.videoPath = [{ name: res.data.trainData.video }]
                this.dataForm.ImgPath = [{ name: res.data.trainData.img }]
                this.$refs.ckEditor && this.$refs.ckEditor.setData(res.data.trainData.content)
              }
            })
          }
        })
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.loading = true
      this.$refs['dataForm'].validate(valid => {
        this.dataForm.sort = this.dataForm.sort || 0
        Object.values(this.test).forEach(x => {
          if (x.selectArray.length > 0) {
            this.dataForm.trainDataQuesIds = [
              ...(this.dataForm.trainDataQuesIds || []),
              ...x.selectArray.map(x => x.id)
            ]
          }
        })
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/train/traindata/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.dataForm
          }).then(res => {
            if (res && res.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                  let that = this
                  setTimeout(function() {
                    that.$refs.ckEditor.setContent('')
                  }, 200)
                }
              })
            } else {
              this.$message.error(res.msg)
            }
            this.loading = false
          })
        }
      })
    },

    // 上传图片
    handleImgProgress() {
      this.loading = true
    },
    handleImgSuccess(res) {
      this.dataForm.imgOssId = res.data.id
      this.loading = false
    },
    handleImgRemove() {
      this.dataForm.imgPath = []
      this.dataForm.imgOssId = ''
    },
    beforeImageUpload(file) {
      let isImg = file.type.split('/')[0] === 'image'
      if (!isImg) {
        this.$message.error('只能上传图片格式!')
      }
      return isImg
    },

    // 上传视频
    handleVideoProgress() {
      this.loading = true
    },
    handleVideoSuccess(res) {
      this.dataForm.videoOssId = res.data.id
      this.dataForm.videoPath = [{ name: res.data.url }]
      this.loading = false
    },
    handleVideoError() {
      this.$message.error('网络错误，上传视频失败!')
    },
    handleVideoRemove() {
      this.dataForm.videoPath = []
      this.dataForm.videoOssId = ''
    },
    beforeVideoUpload(file) {
      let isVideo = file.type.split('/')[0] === 'video'
      if (!isVideo) {
        this.$message.error('只能上传视频格式!')
      }
      return isVideo
    },
    handleExceed() {
      this.$message.error('限制数量为：1')
    }

    // 获取数据列表
    // getDataList () {
    //   this.dataListLoading = true
    //   this.$http({
    //     url: this.$http.adornUrl('/exam-admin/paper/list'),
    //     method: 'post',
    //     data: {
    //       'page': this.pageIndex,
    //       'limit': this.pageSize
    //     }
    //   }).then(data => {
    //     if (data && data.code === 200) {
    //       this.dataList = data.data.list
    //       this.totalPage = data.data.totalCount
    //     } else {
    //       this.dataList = []
    //       this.totalPage = 0
    //     }
    //     this.dataListLoading = false
    //   })
    // }
  }
}
</script>

<style scoped>
</style>
